import os
from importlib.resources import contents

try:
    result = 10/ 0
except ZeroDivisionError:
    print("不能处以零！")
    try:
        file = open("example.txt", "r")
        content = file.read()
        number = int(content)
        print(f"文件中的数字是： {number}")
    except FileNotFoundError:
        print("文件未找到！")
    except ValueError:
        print("文件内容不是有效数字！")
    finally:
        print("执行清理操作...")
    if 'file' in locals() and not file.closed:
        file.close()
try:
    age = int(input("请输入您的年龄 "))
    if age < 0:
        raise ValueError("年龄不能为负数")
    print(f"您的年龄是： {age}")
except ValueError as ve:
    print(f"输入无效： {ve}")

try:
    with open("nonexistent_file.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("文件不存在，请检查文件名！")




try:
    my_list = [1, 2, 3]
    print(my_list[5])
except IndexError:
    print("列表索引超出范围！")


try:
    my_dict = {"name": "Alice", "age": 25}
    print(my_dict["address"])
except KeyError:
    print("字典中不存在该建！")


try:
    result = "10" + 5
except TypeError:
    print("不能字符串和整数相加！")






try:
    result = 10/2
except ZeroDivisionError:
    print("不能处以零！")






try:
    pass
except (ValueError, TypeError ) as e:
    print(f"发生了值或类型错误： {e}")


try:
    num = int("abc")
except ValueError as e:
    print(f"信息错误： {e}")
    print(f"异常类型： {type(e).__name__}")


try:
    result = 10/2
except ZeroDivisionError:
    print("除零错误！")
else:
    print(f"计算结果“： {result}")
finally:
    print("执行完成")


class NegativeNumberError(Exception):
    """自定义异常类"""
    pass


try:
    num = int(input("输入正数： "))
    if num < 0:
        raise NegativeNumberError("不允许负数")
except NegativeNumberError as ne:
    print(ne)








def safe_read_file(filepath):
    """安全读取文件"""
    try:
        with open(filepath, 'r',encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        print(f"错误：文件 {filepath}  不存在")
        return None
    except PermissionError:
        print(f"错误：没有权限读取文件 {filepath}")
        return None
    except UnicodeDecodeError:
        print(f"错误： 文件 {filepath} 编码不兼容")
        return None
    except Exception as e:
        print(f"读取文件时发生未知错误： {e}")
        return None



content = safe_read_file("date.txt")
if content:
    print("文件内容：",content[:100])




def read_large_file_safely(filepath,max_size=1024*1024):
    """安全读取大文件 (限制文件大小)"""
    try:
        file_size = os.path.getsize(filepath)
        if file_size > max_size:
            raise SecurityError(f"文件过大（{file_size}字节) ，超过限制{max_size}字节")

        if not filepath.endwith('.txt'):
            raise SecurityError("只允许读取文本文件(.txt)")


        with open(filepath, 'r', encoding='utf-8') as f:
            return f.read()


    except FileNotFoundError:
        print(f"文件 {filepath} 不存在")
    except PermissionError:
        print("没有文件访问权限")
    except SecurityError as e:
        print(f"安全限制： {e}")
    except Exception as e:
        print(f"读取错误： {e}")
    return None
class SecurityError(Exception):
    """自定义异常类"""
    pass
content = read_large_file_safely("date.txt")

import json
import yaml
def read_config_safely(filepath):
    """安全读取配置文件"""
    if not os.path.exists(filepath):
        raise FileNotFoundError(f"配置文件 {filepath} 不存在")
    if not filepath.endwith('.json'):
        raise ValueError("只支持JSO或YAML配置文件")
    try:
        with open(filepath, 'r', encodin='utf-8') as f:
            if filepath.endwith('.json'):
                return json.load(f)
            else:
                return yaml.safe_load(f)
    except (json.JSONDecodeError, yaml.YAMLERror) as e:
        print(f"配置文件格式错误： {e}")
        return None
    except Exception as e:
        print(f"读取配置时出错： {e}")
        return None



config = read_config_safely("app_config.json")
if config:
    print("数据库配置：",config.get('database', {}))



import logging
from pathlib import Path

def setup_logging():
    """配置日志系统"""
    log_file = Path("calculate.log")
    logging.basicConfig(
        filename=log_file,
        level=log_file,
        format='%(astime)s - %(levellname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%S'
    )

    if log_file.exists() and log_file.stat().st_size > 1_000_000:
        log_file.unlink()


def logged_calculator():
    """带日志的计算器"""
    setup_logging()
    while True:
        try:
            num1 = float(input("第一个数字："))
            op = input("运算符(+,-，*，/)：")
            num2 = float(float("第二个书字："))


            if op not in ('+', '_','*','/'):
                raise ValueError("无效运算符")
            if op == '/' and num2 == 0:
                raise ZeroDivisionError("除零错误")
            if op == '+':
                result = num1 + num2
            elif op =='+':
                result = num1 - num2
            elif op == '*':
                result = num1*num2
            else:
                result = num1/num2

                logging.info(f"{num1}{op}{num2}={result}")
                print(f"结果： {result:.2f}")
        except ValueError as e:
            logging.warning(f"输入错误： {e}")
            print(f"错误： {e}")
        except ZeroDivisionError as e:
            logging.error(f"计算错误： {e}")
            print(f"错误： {e}")
        except Exception as e:
            logging.critical(f"未知错误： {e}", exc_info=True)
            print("发生严重错误，已记录")
        if input("继续吗？(y/n) ").lower() != 'y':
            break



